//
//  RegisteredViewController.m
//  唧歪
//
//  Created by MWJ on 15/7/6.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "RegisteredViewController.h"
#import "AppDelegate.h"
#import "ViewController.h"
#define registeredURL @"https://app.jiwaipro.com:8888/index.php/JiWai/add_registered"  //注册
#define pdURL @"https://app.jiwaipro.com:8888/index.php/JiWai/seek_judge"    //判断
#define loginURL @"https://app.jiwaipro.com:8888/index.php/JiWai/seek_login"   //登陆
#define sendURL @"https://app.jiwaipro.com:8888/index.php/JiWai/sendSMS"   //验证码
#define send1URL @"http://http.yunsms.cn/tx/"

@interface RegisteredViewController (){
    NSString *str1;
    NSString *registerstring;
    NSString *pdstr;
    NSString *send;
    NSString *send1;
    UIAlertView *_alert;
    NSMutableArray *loginArray;
    NSString *loginstr;
    AppDelegate *app;
    NSUserDefaults *defaults;
    int seconds;
    NSTimer *timer;

}

@end

@implementation RegisteredViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"注册/登陆";
    [self.button.layer setMasksToBounds:YES];
    [self.button.layer setCornerRadius:5.0];
    [self.cofbutton.layer setMasksToBounds:YES];
    [self.cofbutton.layer setCornerRadius:5.0];
    app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    self.phone.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.number.clearButtonMode =UITextFieldViewModeWhileEditing;
    
//    self.phone.delegate = self;
//    self.number.delegate =self;
    
    //return键改成Done键
    self.phone.keyboardType = UIKeyboardTypeNumberPad;
    self.number.keyboardType = UIKeyboardTypeNumberPad;
//    self.phone.returnKeyType =UIReturnKeyDone;
//    self.number.returnKeyType =UIReturnKeyDone;
    // Do any additional setup after loading the view.
}
#pragma mark - 注册时候解析数据
-(void)registeredData{
    //判断号码、验证码是否为空
    if ([self.phone.text isEqualToString:@""] || [self.number.text isEqualToString:@""]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"手机号或验证码不能为空" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }else{
        NSString *poststr =[NSString stringWithFormat:@"user_phone=%@&user_validation=%@",self.phone.text,self.number.text];
        [self londingPath:registeredURL Str:poststr];
    }
}
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        registerstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:registerstring waitUntilDone:YES];
    }];
}
-(void)refreshData:(NSString *)sender{
    if ([registerstring isEqualToString:@"用户名已存在"]) {
    }else{
        int intStr = [registerstring intValue];
        if (intStr == 0) {
        }else{
            app.user_id = registerstring;
            NSString *poststr =[NSString stringWithFormat:@"mobile=%@",self.phone.text];
            [self londingPathsend:sendURL Strsend:poststr];
        }
    }
}
-(void)londingPathsend:(NSString *)path Strsend:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        send = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshDatasend:) withObject:send waitUntilDone:YES];
    }];
}
-(void)refreshDatasend:(NSString *)sender{
    NSString *utf = @"&encode=utf8";
    NSString *poststr = [NSString stringWithFormat:@"%@%@",send,utf];
    [self londingPathsend1:send1URL Strsend1:poststr];
}
-(void)londingPathsend1:(NSString *)path Strsend1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        send1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshDatasend1:) withObject:send1 waitUntilDone:YES];
    }];
}
-(void)refreshDatasend1:(NSString *)sender{
    if ([send1 isEqualToString:@"100"]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"验证码发送成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)obtain:(id)sender {
    [app isConnectionAvailable];
    if ([app.Existence isEqualToString:@"1"]) {
    }else{
    app.Existence = @"0";
    if ([self.phone.text isEqualToString:@""]) {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入手机号码" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}else{
    loginstr =[NSString stringWithFormat:@"user_phone=%@",self.phone.text];
    [self londingPathpd:pdURL Strpd:loginstr];
    //显示时间结束后，执行事件
    timer=[[NSTimer alloc]init];
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
}
    }
}
-(void)londingPathpd:(NSString *)path Strpd:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        pdstr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshDatapd:) withObject:pdstr waitUntilDone:YES];
    }];
}
-(void)refreshDatapd:(NSString *)sender{
    if ([pdstr isEqualToString:@"1"]) {
        NSString *poststr =[NSString stringWithFormat:@"mobile=%@",self.phone.text];
        [self londingPathsend:sendURL Strsend:poststr];
    }else{
        NSString *poststr =[NSString stringWithFormat:@"user_phone=%@",self.phone.text];
        [self londingPath:registeredURL Str:poststr];
    }
}
//倒计时方法验证码实现倒计时60秒，60秒后按钮变换开始的样子
-(void)timerFireMethod:(NSTimer *)theTimer {
    if (seconds+60 == 1) {
        [theTimer invalidate];
        seconds = 0;
        [self.cofbutton setTitle:@"获取验证码" forState: UIControlStateNormal];
        [self.cofbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.cofbutton setEnabled:YES];
        
    }else{
        
        seconds--;
        NSString *title = [NSString stringWithFormat:@"%d秒",seconds+60];
        [self.cofbutton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self.cofbutton setEnabled:NO];
        [self.cofbutton setTitle:title forState:UIControlStateNormal];
        
        
    }
    
}
//如果登陆成功，停止验证码的倒数，
- (void)releaseTImer {
    if (timer) {
        if ([timer respondsToSelector:@selector(isValid)]) {
            if ([timer isValid]) {
                [timer invalidate];
                seconds = 60;
            }
        }
    }
}
- (IBAction)registerUser:(id)sender {
    [app isConnectionAvailable];
    if ([app.Existence isEqualToString:@"1"]) {
    }else{
    app.Existence = @"0";
    //判断号码、验证码是否为空
    if ([self.phone.text isEqualToString:@""] || [self.number.text isEqualToString:@""]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"手机号或验证码不能为空" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }else{
        NSString *poststr =[NSString stringWithFormat:@"user_phone=%@&user_validation=%@",self.phone.text,self.number.text];
        [self londingPathlogin:loginURL Strlogin:poststr];
    }
    }
}
//#pragma mark - 登陆
-(void)londingPathlogin:(NSString *)path Strlogin:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        loginArray = [NSMutableArray array];
        loginArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:loginArray waitUntilDone:YES];
    }];
}
-(void)refreshData1:(NSMutableArray *)sender{
    for (NSDictionary *dic in sender) {
        if (sender.count !=0) {
        app.user_id = dic[@"user_id"];
        defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:dic[@"user_id"] forKey:@"yonghu"];
        ViewController *VC=[self.storyboard instantiateViewControllerWithIdentifier:@"homeVC"];
        [self.navigationController pushViewController:VC animated:YES];
        [self releaseTImer];
        }else{
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您输入的手机号或者验证码有误，请重新输入！" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
    }
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //doneButton.hidden = YES;
    [self.phone resignFirstResponder];
    [self.number resignFirstResponder];
}
//#pragma mark - 点击换行完成编辑
//-(BOOL)textFieldShouldReturn:(UITextField *)textField{
//    
//    if (self.phone== textField || self.number == textField) {
//        [self.phone resignFirstResponder];
//        [self.number resignFirstResponder];
//    }
//    return YES;
//    
//}

@end
